/**
 * 图片上传组件
 * 
 * 支持点击上传、拖拽上传、图片预览、进度显示等功能
 */
import React, { useRef, useState, useEffect } from 'react';
import { useImageUpload, useDragUpload } from '@/hooks/useUpload';
import { cn } from '@/lib/utils';

interface ImageUploadProps {
  value?: string;
  onChange?: (url: string) => void;
  onError?: (error: string) => void;
  className?: string;
  disabled?: boolean;
  accept?: string;
  maxSize?: number; // MB
  width?: number;
  height?: number;
  placeholder?: string;
  showProgress?: boolean;
  autoCompress?: boolean;
}

export default function ImageUpload({
  value,
  onChange,
  onError,
  className,
  disabled = false,
  accept = 'image/*',
  maxSize = 5,
  width = 160,
  height = 80,
  placeholder = '点击或拖拽上传图片',
  showProgress = true,
  autoCompress = true
}: ImageUploadProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [currentImage, setCurrentImage] = useState<string>(value || '');

  // 同步外部value到内部状态
  useEffect(() => {
    setCurrentImage(value || '');
  }, [value]);

  // 使用拖拽上传Hook
  const {
    isUploading,
    progress,
    error,
    uploadFile,
    isDragOver,
    dragHandlers,
    reset
  } = useDragUpload({
    autoCompress,
    onSuccess: (result) => {
      setCurrentImage(result.url);
      onChange?.(result.url);
    },
    onError: (errorMessage) => {
      onError?.(errorMessage);
    }
  });

  // 处理文件选择
  const handleFileSelect = async (file: File) => {
    // 验证文件大小
    if (file.size > maxSize * 1024 * 1024) {
      const errorMessage = `文件大小不能超过 ${maxSize}MB`;
      onError?.(errorMessage);
      return;
    }

    try {
      await uploadFile(file);
    } catch (err) {
      // 错误已经在Hook中处理
    }
  };

  // 处理点击上传
  const handleClick = () => {
    if (disabled || isUploading) return;
    fileInputRef.current?.click();
  };

  // 处理文件输入变化
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      handleFileSelect(file);
    }
    // 清空input值，允许重复选择同一文件
    e.target.value = '';
  };

  // 处理删除图片
  const handleRemove = (e: React.MouseEvent) => {
    e.stopPropagation();
    setCurrentImage('');
    onChange?.('');
    reset();
  };

  return (
    <div className={cn('relative', className)}>
      {/* 隐藏的文件输入 */}
      <input
        ref={fileInputRef}
        type="file"
        accept={accept}
        onChange={handleFileChange}
        className="hidden"
        disabled={disabled}
      />

      {/* 上传区域 */}
      <div
        onClick={handleClick}
        {...dragHandlers}
        className={cn(
          'relative border-2 border-dashed rounded-lg transition-all duration-200 cursor-pointer',
          'flex items-center justify-center overflow-hidden',
          {
            'border-blue-400 bg-blue-50': isDragOver && !disabled,
            'border-gray-300 hover:border-blue-400 hover:bg-gray-50': !isDragOver && !disabled && !currentImage,
            'border-green-300 bg-green-50': currentImage && !isDragOver,
            'border-gray-200 bg-gray-100 cursor-not-allowed': disabled,
            'border-red-300 bg-red-50': error
          }
        )}
        style={{ width, height }}
      >
        {/* 加载状态 */}
        {isUploading && (
          <div className="absolute inset-0 bg-white bg-opacity-90 flex items-center justify-center z-10">
            <div className="text-center">
              <i className="fa-solid fa-spinner fa-spin text-2xl text-blue-600 mb-2"></i>
              {showProgress && progress && (
                <div className="text-sm text-gray-600">
                  {progress.percentage}%
                </div>
              )}
            </div>
          </div>
        )}

        {/* 图片预览 */}
        {currentImage && !isUploading && (
          <>
            <img
              src={currentImage}
              alt="Preview"
              className="w-full h-full object-cover"
            />
            {/* 删除按钮 */}
            <button
              type="button"
              onClick={handleRemove}
              className="absolute -top-2 -right-2 w-8 h-8 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 transition-colors shadow-lg z-20"
              disabled={disabled}
              style={{ zIndex: 20 }}
            >
              <i className="fa-solid fa-times text-sm"></i>
            </button>
            {/* 重新上传遮罩 */}
            <div className="absolute inset-0 bg-black bg-opacity-0 hover:bg-opacity-30 transition-all duration-200 flex items-center justify-center">
              <div className="text-white opacity-0 hover:opacity-100 transition-opacity">
                <i className="fa-solid fa-upload text-lg"></i>
              </div>
            </div>
          </>
        )}

        {/* 空状态 */}
        {!currentImage && !isUploading && (
          <div className="text-center p-4">
            <i className={cn(
              'fa-solid fa-cloud-upload text-3xl mb-2',
              {
                'text-blue-400': isDragOver,
                'text-gray-400': !isDragOver && !error,
                'text-red-400': error
              }
            )}></i>
            <p className={cn(
              'text-sm',
              {
                'text-blue-600': isDragOver,
                'text-gray-600': !isDragOver && !error,
                'text-red-600': error
              }
            )}>
              {error || placeholder}
            </p>
            <p className="text-xs text-gray-500 mt-1">
              支持 JPG、PNG、WebP 格式
            </p>
            <p className="text-xs text-gray-500">
              最大 {maxSize}MB
            </p>
          </div>
        )}
      </div>

      {/* 进度条 */}
      {isUploading && showProgress && progress && (
        <div className="mt-2">
          <div className="flex justify-between text-xs text-gray-600 mb-1">
            <span>上传中...</span>
            <span>{progress.percentage}%</span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-1">
            <div
              className="bg-blue-600 h-1 rounded-full transition-all duration-300"
              style={{ width: `${progress.percentage}%` }}
            ></div>
          </div>
        </div>
      )}

      {/* 错误信息 */}
      {error && (
        <div className="mt-2 text-sm text-red-600 flex items-center">
          <i className="fa-solid fa-exclamation-triangle mr-1"></i>
          {error}
        </div>
      )}
    </div>
  );
}
